<template>
	<agent-user-table
		ref="agentUserTableRef"
		v-model="value"
		:title="t('选择代理商')"
		:service="service.agent.agent"
		:columns="columns"
		:multiple="multiple"
		:apiPage="'getAgentList'"
		:paramsObj="{
			level: props.agentLevel,
			parentAgentId: props.parentAgentId,
			agentChangeType: props.agentChangeType,
			functionType: props.functionType,
			agentUserId: props.agentUserId
		}"
		:dict="{ text: 'label', id: 'value' }"
		:userName="userName"
		pickerType="text"
		:disabled="props.disabled"
	/>
</template>

<script setup lang="ts">
defineOptions({
	name: 'agent-user-select'
});

import { useCool } from '/@/cool';
import { useI18n } from 'vue-i18n';
import { CrudProps } from '/#/crud';
import { reactive, ref, useModel, watch } from 'vue';
import AgentUserTable from './agent-user-table.vue';

const props = defineProps({
	...CrudProps,
	modelValue: null,
	multiple: Boolean,
	agentLevel: {
		type: Number,
		required: true
	},
	parentAgentId: {
		type: Number,
		default: null
	},
	agentChangeType: {
		type: String,
		default: 'agent'
	},
	disabled: {
		type: Boolean,
		default: false
	},
	functionType: {
		type: String,
		default: 'add'
	},
	agentUserId: {
		type: Number,
		default: null
	},
	agentObj: {
		type: Object,
		default: () => ({})
	}
});

const { service } = useCool();
const { t } = useI18n();

const value = useModel(props, 'modelValue');
const agentUserTableRef = ref();
const userName = ref('');

// 监听agentObj变化，更新modelValue
watch(
	() => props.agentObj,
	newAgentObj => {
		// console.log('Agent user select - agentObj changed:', newAgentObj);
		if (newAgentObj && newAgentObj.agentUserId && props.agentChangeType == 'agent') {
			// 当agentObj变化时，将agentUserId设置为modelValue
			value.value = newAgentObj.agentUserId;
			userName.value = newAgentObj.agentName || '';
			console.log('Agent user select - userName updated:', newAgentObj.agentName);
		} else if (newAgentObj && props.agentChangeType == 'leaderAgent') {
			console.log(
				'Agent user select - parentAgentName updated:',
				newAgentObj.parentAgentUser
			);
			userName.value = newAgentObj.parentAgentUser || '';
			value.value = newAgentObj.parentAgentId || '';
		}
		// console.log(props.agentChangeType);
	},
	{ immediate: true, deep: true }
);

// 清空数据
function clearTableData() {
	if (agentUserTableRef.value && agentUserTableRef.value.clearData) {
		agentUserTableRef.value.clearData();
	}
}

defineExpose({
	clearTableData
});

const columns = ref([
	{ label: t('ID'), prop: 'value', minWidth: 140 },
	{ label: t('代理商名称'), prop: 'label', minWidth: 140 },
	{ label: t('描述'), prop: 'agentDescription', minWidth: 140 }
]);
</script>
